﻿using System;
using System.Collections;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Networking;

namespace CJ.XNFZ {
    public class XNFZTemplateHelper : Singleton<XNFZTemplateHelper> {

        [DllImport ("__Internal")]
        private static extern string _GetSearchString (string key);

        [DllImport ("__Internal")]
        private static extern string _SetName (string id);

        /// <summary>
        /// 在streamingassets下读取文件找到IP
        /// </summary>
        public void GetConfig (string filepath, Action<string> ok = null, Action<string> error = null) {
            string path = Application.streamingAssetsPath + "/" + filepath;
            if (!path.Contains ("://")) path = "file://" + path;
            StartCoroutine (_GetConfig (path, ok, error));
        }

        /// <summary>
        /// 外部读取ip
        /// </summary>
        /// <param name="a"></param>
        /// <returns></returns>
        private IEnumerator _GetConfig (string path, Action<string> ok = null, Action<string> error = null) {
            UnityWebRequest req = UnityWebRequest.Get (path);
            yield return req.SendWebRequest ();
            if (req.isNetworkError || req.isHttpError) {
                Debug.LogError ("read StreamingAssets file error：" + req.error + " " + path);
                if (error != null) error ("网络错误");
            } else {
                var config = req.downloadHandler.text;
                if (ok != null) ok (config);
            }
        }

        public string GetSearchString (string key) {
            if (Application.isEditor) return null;
            return _GetSearchString (key);
        }

        public void ShowName (string name) {
            if (Application.isEditor) return;
            _SetName (name);
        }

        public void HideName () {
            if (Application.isEditor) return;
            _SetName ("");
        }
    }

}